<template>
  <div class="login-container">
    <div class="login">
      <h2>学生综合信息管理系统</h2>
      <form>
        <div class="form-group">
          <label for="username">用户名:</label>
          <input type="text" id="username" v-model="username" />
        </div>
        <div class="form-group">
          <label for="password">密码:</label>
          <input type="password" id="password" v-model="password"/>
        </div>
        <button type="submit" class="login-button" @click="handleSend1">登录</button>
      </form>
      <p v-if="errorMessage" class="error" >{{ errorMessage }}</p>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data () {
    return {
      username: '',
      password: '',
      errorMessage: ''
    }
  },
  methods: {
    handleSend1 () {
    // 验证用户名和密码是否为空
      if (!this.username || !this.password) {
        this.errorMessage = '用户名和密码不能为空'
        return
      }
      // 通过axiox发送post请求
      axios
        .post('/api/login', {
          username: this.username,
          password: this.password
        })
        .then((res) => {
          if (res.data.code === '200') {
            const token = res.data.data.token
            const power = res.data.data.power
            // 将 token 保存到 localStorage
            sessionStorage.setItem('authToken', token)
            sessionStorage.setItem('userPower', power)

            // 登录成功后跳转到首页h
            this.$router.push({ name: 'home' })
          } else {
            this.errorMessage = res.data.message
          }
        })
        .catch((error) => {
          this.errorMessage = error
          console.error(error)
        })
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-image: url("../static/0183c657b3bf650000012e7e841005.webp"); /* Specify the path to the background image */
  background-size: cover;
  background-position: center;
}

.login {
  width: 300px;
  padding: 20px;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.form-group {
  margin-bottom: 15px;
}

input[type="text"],
input[type="password"] {
  width: 100%;
  padding: 8px;
  margin-top: 5px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.login-button {
  width: 100%;
  padding: 10px;
  background-color: #5cb85c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.login-button:hover {
  background-color: #4cae4c;
}

.error {
  color: red;
  margin-top: 10px;
}
</style>
